<?php

namespace app\modules\api;

use app\models\MiniprogramSession;
use app\models\User;
use app\models\UserAttr;
use app\models\UserRoleData;
use Yii;
use yii\web\Controller;

/**
 * Default controller for the `api` module
 */
class CommonController extends Controller
{
    public $layout = false;
    protected $paras;
    protected $check_login = 1;
    protected $sid;
    protected $uid;
    protected $session;
    protected $user;
    protected $openid;
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        set_exception_handler([$this, 'error']);

    }
    //统一报错AJAX
    public function error(\Throwable $e){

        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        $errmsg = $e->getMessage();
        if(YII_DEBUG){
            $errmsg.=$e->getFile().$e->getLine();
        }
        else{
            Yii::error($errmsg.$e->getFile().$e->getLine());
        }
        echo json_encode(['errcode'=>$e->getCode(),'errmsg'=>$errmsg],JSON_UNESCAPED_UNICODE);
    }
    //统一成功JAX
    protected function success($arr = []){

        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        return json_encode(array_merge(['errcode'=>0,'errmsg'=>'','result'=>$arr]),JSON_UNESCAPED_UNICODE);
    }
    //获取用户ID
    protected function getUid(){
        if(!empty($this->user)) return $this->user->id;
        return 0;
    }
    //获取用户ID
    protected function getOpenid(){
        if(empty($this->openid)) return $this->openid;

    }
    //检查权限
    protected function checkAuth($type,$type_id,$role_id){
        if(empty($type_id)) return ;
        $count = UserRoleData::find()->where([
            'uid'=>$this->getUid(),
            'type'=>$type,
            'type_id'=>$type_id,
            'role_id'=>$role_id,
        ])->count();
        if($count==0){
            throw new \Exception('无权操作', 1);
        }
    }
    public function beforeAction($action)
    {
        $this->sid = Yii::$app->request->post('sid','');
        if($this->sid){
            $this->session = MiniprogramSession::getObjBySid($this->sid);
            if(!empty($this->session)){
                $this->user = User::getObjByMiniOpenid($this->session->openid);
            }
        }
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }
}
